#include <iostream>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <string> 
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

#include "signIn.hpp"

void *file_server(void* ptr)
{
	signIn *si = reinterpret_cast<signIn *>(ptr);
	int portno = 7171;
	int new_sockfd;
	void *retval = NULL;
	int serverfd = ::socket(AF_INET, SOCK_STREAM, 0);
	if (serverfd < 0) {
		std::cerr << "ERROR opening socket" << std::endl;
		return retval;
	}
	sockaddr_in serv_addr;
	memset(&serv_addr, 0, sizeof(sockaddr_in));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = INADDR_ANY;
	serv_addr.sin_port = htons(portno);
	if(bind(serverfd, (sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
		std::cerr << "Can't bind socket: errno " << errno << std::endl;
		return retval;
	}
	listen(serverfd, 100);
	sockaddr_in cli_addr;
	socklen_t cli_len = sizeof(cli_addr);
	std::cout << "file server run successfully " << std::endl;
	while(true){
		new_sockfd = ::accept(serverfd, (sockaddr*)&cli_addr, &cli_len);
		char* host_name = inet_ntoa(cli_addr.sin_addr);
		std::cout << "transfering file from: "
		       	<< host_name << std::endl; 

		char buff[255];
		int n = ::read(new_sockfd, buff, 255);
		if(n < 0)
			std::cout << "Error getting file information\n";
		write(new_sockfd,"0",1);
		char *file_name = new char[n+1];
		strncpy(file_name, (char*)buff, n);
		file_name[n] = '\0';
		std::cout << file_name << std::endl;
		off_t file_size;
		n = ::read(new_sockfd, &file_size, sizeof(off_t));
		si->w->e_file_request(new_sockfd,file_name, (int)file_size);
	}
	return retval;
}
